﻿using System;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web.Caching;
using System.Web.UI.WebControls;
using System.Xml;
using DFT.DB;
using DFT.Infos;
using TreeGenerator;
using System.IO;

namespace DFT
{
    public partial class DisplayTree : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DataTable profilesTable = new DataTable("profiles");
            if (DBManager.GetAllProfilesUser(((UserInfo)Session["userInfo"]).UserId, ref profilesTable))
            {
                GenerateChart(profilesTable, profilesTable.Select("parentProfId Is NULL")[0]["profId"].ToString());
            }
        }

        private void GenerateChart(DataTable profilesTable, String mItem)
        {
            //crate the chart object
            TreeData.TreeDataTableDataTable treeTable = new TreeData.TreeDataTableDataTable();
            GetDT(treeTable, profilesTable, mItem);
            TreeBuilder currentBOM = new TreeBuilder(treeTable);

            //specify visual properties
            currentBOM.HorizontalSpace = 10;
            currentBOM.VerticalSpace = 10;
            currentBOM.FontSize = 8;
            currentBOM.BoxHeight = 80;
            currentBOM.BoxWidth = 80;
            currentBOM.HasLogo = true;
            currentBOM.LogoHeight = 40;
            currentBOM.LogoWidth = 40;
            currentBOM.LogoMargin = 10;
            currentBOM.LineColor = ColorTranslator.FromHtml("#BFBFC9");
            currentBOM.FontColor = ColorTranslator.FromHtml("#3B4164");
            System.Drawing.Image OC = System.Drawing.Image.FromStream(currentBOM.GenerateTree(mItem, ImageFormat.Bmp));

            string nameOfImage = Session.SessionID + "CurrentImage";
            //save in the cache, to be used by the page creating the image
            Cache.Insert(nameOfImage, OC, null, DateTime.MaxValue, TimeSpan.FromMinutes(1), CacheItemPriority.NotRemovable, null);
            //update the item image map
            //supply the image name by querystring
            impBOM.ImageUrl = "AJAX/OrgChartImage.aspx?ID=" + nameOfImage;
            //remove all hotspots
            impBOM.HotSpots.Clear();
            //regenerate the hotspots.
            foreach (XmlNode oNode in currentBOM.xmlTree.SelectNodes("//Node"))
            {
                RectangleHotSpot RectHS = new RectangleHotSpot();
                RectHS.HotSpotMode = HotSpotMode.Navigate;
                Rectangle currentRect = currentBOM.getRectangleFromNode(oNode);
                RectHS.Top = currentRect.Top;
                RectHS.Bottom = currentRect.Bottom;
                RectHS.Left = currentRect.Left;
                RectHS.Right = currentRect.Right;
                //RectHS.PostBackValue = oNode.Attributes["nodeID"].InnerText;
                RectHS.AlternateText = oNode.Attributes["nodeDescription"].InnerText;
                RectHS.NavigateUrl = "javascript:ProfileForm('Show','" + oNode.Attributes["nodeID"].InnerText + "','','');";
                impBOM.HotSpots.Add(RectHS);
            }
        }
        private void GetDT(TreeData.TreeDataTableDataTable treeTable, DataTable profilesTable, String rootId)
        {
            DataRow rootProfile = profilesTable.Select("profId =" + rootId)[0];
            TreeData.TreeDataTableRow rootRow = treeTable.NewTreeDataTableRow();
            String parentProfId = rootProfile["parentProfId"] == DBNull.Value ? "" : rootProfile["parentProfId"].ToString();
            rootRow.nodeID = rootProfile["profId"].ToString();
            rootRow.parentNodeID = parentProfId;
            rootRow.nodeDescription = rootProfile["firstName"].ToString() + " " + rootProfile["lastName"].ToString();
            rootRow.nodeNote = "";
            Byte[] imageByte = new Byte[0];
            String imageType = "";
            if (DBManager.GetImage(Int64.Parse(rootId), ref imageByte, ref imageType))
            {
                if (String.IsNullOrEmpty(imageType) || imageByte.Length == 0)
                {
                    String imagePath = "~/images/male.gif";
                    if (rootProfile["gender"].ToString() == "f")
                    {
                        imagePath = "~/images/female.gif";
                    }
                    FileStream streamObj = File.OpenRead(Page.MapPath(imagePath));
                    imageByte = new Byte[streamObj.Length];
                    streamObj.Read(imageByte, 0, imageByte.Length);
                }
            }
            rootRow.nodeImage = imageByte;
            treeTable.AddTreeDataTableRow(rootRow);
            foreach (DataRow childProfile in profilesTable.Select("parentProfId =" + rootProfile["profId"].ToString()))
            {
                GetDT(treeTable, profilesTable, childProfile["profId"].ToString());
            }
        }
    }
}